package pub.tbc.toolkit.http2;

//import

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import lombok.Builder;
import lombok.Data;
import org.apache.http.HttpResponse;
import org.apache.http.client.fluent.Request;
import pub.tbc.toolkit.Factory;
import pub.tbc.toolkit.Objs;

import java.io.IOException;
import java.util.Map;

/**
 * @author tbc on 2016/9/18 09:40:43.
 */
@Data
@Builder
public class ResponseWrapper {
    private int httpCode;
    private String contentType;
    private String message;
    private String result;
    private HttpResponse httpResponse;

    private void checkRequestStatus() {
        if (isNotOk()) {
            throw new RuntimeException("请求外部系统失败");
        }
        if (isNotJSON() || Objs.isEmpty(result)) {
            throw new RuntimeException("外部系统未返回有效JSON数据");
        }
    }

    public boolean isOk() {
        return httpCode == 200;
    }

    public boolean isNotOk() {
        return !isOk();
    }

    public boolean isJSON() {
        return "application/json".equals(contentType);
    }

    public boolean isNotJSON() {
        return !isJSON();
    }


    /**
     * 去掉外层包装后的实际数据
     *
     * @param key -> 包装内实际数据的Key
     * @param <T>
     * @return
     */
    public <T> T getNeatResult(String key) {
        Map<String, Object> reslutMap = toMap();
        if (isNotOk() || isNotJSON() || Objs.isEmpty(reslutMap)) {
            throw new RuntimeException("请求外部系统失败");
        }
        return (T) reslutMap.get(key);
    }

    public String getNeatJSON(String key) {
        JSONObject json = JSON.parseObject(result);
        Object data = json.get(key);
        return JSON.toJSONString(data);
    }

    public Map<String, Object> getResultMap() {
        return toMap();
    }

    public <T> T toBean(Class<T> c) {
        checkRequestStatus();
        return JSON.parseObject(result, c);
    }

    public Map<String, Object> toMap() {
        checkRequestStatus();
        return JSON.parseObject(result);
    }

    public static void main(String[] args) throws IOException {
        String str = "a";
        System.out.println(JSON.toJSONString(1));
//        HttpClient client = null;
//        HttpResponse response =
//        Header con = client.execute(new HttpGet("")).getEntity().getContentType();
        System.out.println(Request.Get("http://192.168.1.11:22100/yijiajiao-wares/basic/grades").execute().returnResponse().getEntity().getContentType().getValue());

        System.out.println(JSON.toJSONString(Factory.asArrayList(Factory.asHashMap("k1", 1, "k2", "v2"))));
    }

}
